let currentCount = 0
let map = new Map()
const promise = (
  callback: (
    resolve: (value: unknown) => void,
    reject: (reason?: any) => void
  ) => void
) => {
  if (map.get(currentCount)) {
    const res = map.get(currentCount)
    currentCount++
    return res
  }
  const p = new Promise(callback)
  throw p
}

const run = (action: () => void) => {
  try {
    action()
  } catch (error: any) {
    error
      .then((res: any) => {
        map.set(currentCount, res)
      })
      .catch((error_: any) => {
        map.set(currentCount, error_)
      })
      .finally(() => {
        currentCount = 0
        run(action)
      })
  }
}

const execute = (task: any) => {
  currentCount = 0
  map = new Map()
  run(task)
}

export const KillAwaitPromise = {
  execute,
  promise
}

export default KillAwaitPromise
